package com.topisv.tms.web.returnGood;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.ReturnGood;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillItemPre;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillPre;
import com.topisv.tms.entity.stock.instorage.pre.PreInBill;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.returnGood.returnGoodService;
import com.topisv.tms.service.stock.instorage.InstorageBillService;
import com.topisv.tms.service.stock.instorage.PreInBillService;
import com.topisv.tms.service.stock.preinstorage.PreInstorageService;
import com.topisv.tms.web.base.BaseDataTableController;

@Controller
@RequestMapping(value="/v2/returnGood")
public class returnGoodController extends BaseDataTableController{

	@Autowired
	private returnGoodService returnGoodService;
	@Autowired
	private InstorageBillService instorageBillService;
	@Autowired
	private PreInBillService preInBillService;
	@Autowired
	private PreInstorageService preInstorageService;
	
	@RequestMapping(value="returnGoodList")
	public String list(){
		return "returnGood/returnGoodList";
	}
	
	@RequestMapping(value="page")
	public void page(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			// 客户端参数
			QueryParamHolder paramHolder = collectParam(paramJson,"_");
			Map<String, Object> searchParams = paramHolder.getSearchParams();
			String fromTm = (String)searchParams.get("GTE_createTime");
			String toTm = (String)searchParams.get("LT_createTime");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(!StringUtils.isBlank(fromTm)){
				searchParams.put("GTE_createTime",sdf.parse(fromTm));
			}
			if(!StringUtils.isBlank(toTm)){
				searchParams.put("LT_createTime",sdf.parse(toTm));
			};
			Page<ReturnGood> page = returnGoodService.getReturnGood(paramHolder);
			// 封装查询结果
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping(value="returnGood_create",method=RequestMethod.GET)
	public String returnGoodCreate(Model model){
		model.addAttribute("status", 0);
		model.addAttribute("action", "returnGood_save");
		return "returnGood/returnGoodCreate";
	}
	
	@RequestMapping(value="returnGood_save",method=RequestMethod.POST)
	public String  addReturnGood(@Valid ReturnGood returngood, 
			ServletRequest request,ServletResponse response,RedirectAttributes redirectAttributes){
		try {
			returngood.setCreateTime(new Date()); //设置创建时间
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			returngood.setRegister(curUser.getRealname());
			String oldexpressno = returngood.getOldExpress(); //获取前端来的原快递单号
			String returnexpressno = returngood.getReturnExpress();//获取退货快递单号
			String oldorderno = returngood.getOldOrderNo();		//获取原订单号
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("returnexpressno", returnexpressno);
			map.put("oldorderno", oldorderno);
			map.put("oldexpressno", oldexpressno);
			
			if(!oldexpressno.isEmpty()||!returnexpressno.isEmpty()||!oldorderno.isEmpty()){
				InstorageBillPre billPre = returnGoodService.findReturnGoodByWhere(map);
					if(billPre != null){
						List<InstorageBillItemPre> itemPreList = preInstorageService.fiindByBillPreId(billPre.getId());
						//判断有没有正品
						if(itemPreList.size()==0){
							billPre.setReturngoodStatus("1");
							instorageBillService.addInstorageBillPre(billPre);
							returngood.setInbillCode(findInbillCode(billPre.getId()));
							returngood.setStatus("1");
							returnGoodService.saveReturnGood(returngood);
							redirectAttributes.addFlashAttribute("message", "创建成功 ,且预约池中有该单的数据");
						}else{
							returngood.setRemark("此单有正品");
							returngood.setStatus("0");
							returnGoodService.saveReturnGood(returngood);
							redirectAttributes.addFlashAttribute("message", "<span style=\"color:red;\"><h4>匹配成功,此单有正品,请处理。。。</h4></span>");
						}
						
				}else{
					returngood.setStatus("0");
					returnGoodService.saveReturnGood(returngood);
					redirectAttributes.addFlashAttribute("message", "创建成功");
				}
			}else{
					returngood.setStatus("0");
					returnGoodService.saveReturnGood(returngood);
					redirectAttributes.addFlashAttribute("message", "创建成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "创建失败");
		}
		return "redirect:/v2/returnGood/returnGoodList";
	}
	
	@RequestMapping(value="updateRg/{id}", method = RequestMethod.GET)
	public String updateReturnGood(@PathVariable(value="id") Long id,Model model){
		ReturnGood returnGood = returnGoodService.findRg(id);
		model.addAttribute("returngood", returnGood);
		model.addAttribute("status", 1);
		model.addAttribute("action", "update");
		return "returnGood/returnGoodCreate";
	}
	  
	@RequestMapping(value="update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("returngood") ReturnGood returngood,
			RedirectAttributes redirectAttributes){
		try {
			String oldexpressno = returngood.getOldExpress(); //获取前端来的原快递单号
			String returnexpressno = returngood.getReturnExpress();//获取退货快递单号
			String oldorderno = returngood.getOldOrderNo();		//获取原订单号
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("returnexpressno", returnexpressno);
			map.put("oldorderno", oldorderno);
			map.put("oldexpressno", oldexpressno);
			if(!oldexpressno.isEmpty()||!returnexpressno.isEmpty()||!oldorderno.isEmpty()){
				InstorageBillPre billPre = returnGoodService.findReturnGoodByWhere(map);
				if(billPre != null){
					List<InstorageBillItemPre> itemPreList = preInstorageService.fiindByBillPreId(billPre.getId());
					//判断有没有正品
					if(itemPreList.size()==0){
						billPre.setReturngoodStatus("1");
						instorageBillService.addInstorageBillPre(billPre);
						returngood.setInbillCode(findInbillCode(billPre.getId()));
						returngood.setStatus("1");
						returnGoodService.saveReturnGood(returngood);
						redirectAttributes.addFlashAttribute("message", "更新成功 ,且预约池中有该单的数据");
					}else{
						returngood.setRemark("此单有正品");
						returngood.setStatus("0");
						returnGoodService.saveReturnGood(returngood);
						redirectAttributes.addFlashAttribute("message", "<span style=\"color:red;\"><h4>匹配失败,此单有正品,请处理。。。</h4></span>");
						redirectAttributes.addFlashAttribute("msg","更新成功，此单有正品");
					}
			}else{
				returngood.setStatus("0");
				returnGoodService.saveReturnGood(returngood);
				redirectAttributes.addFlashAttribute("message", "更新成功");
			}
			}else{
				returngood.setStatus("0");
				returnGoodService.saveReturnGood(returngood);
				redirectAttributes.addFlashAttribute("message", "更新成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "更新失败");
		}
		return "redirect:/v2/returnGood/returnGoodList";
	}
	
	@RequestMapping(value="match")
	@ResponseBody
	public String match(Model model,RedirectAttributes redirectAttributes,ServletRequest req){
		try {
			Long id = Long.valueOf(req.getParameter("id"));
			ReturnGood returngood = returnGoodService.findRg(id);
			String oldexpressno = returngood.getOldExpress(); //获取前端来的原快递单号
			String returnexpressno = returngood.getReturnExpress();//获取退货快递单号
			String oldorderno = returngood.getOldOrderNo();		//获取原订单号
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("returnexpressno", returnexpressno);
			map.put("oldorderno", oldorderno);
			map.put("oldexpressno", oldexpressno);
			if(!oldexpressno.isEmpty()||!returnexpressno.isEmpty()||!oldorderno.isEmpty()){
				InstorageBillPre billPre = returnGoodService.findReturnGoodByWhere(map);
				if(billPre != null){
					List<InstorageBillItemPre> itemPreList = preInstorageService.fiindByBillPreId(billPre.getId());
					if(itemPreList.size()==0){
						billPre.setReturngoodStatus("1");
						instorageBillService.addInstorageBillPre(billPre);
						returngood.setInbillCode(findInbillCode(billPre.getId()));
						returngood.setStatus("1");
						returnGoodService.saveReturnGood(returngood);
					redirectAttributes.addFlashAttribute("message", "匹配成功");
					return "true";
					}else{
						returngood.setRemark("此单有正品");
						returngood.setStatus("0");
						returnGoodService.saveReturnGood(returngood);
						redirectAttributes.addFlashAttribute("message", "<span style=\"color:red;\"><h4>匹配失败,此单有正品,请处理。。。</h4></span>");
						return "false";
					}
			}else{
				returngood.setStatus("0");
				returnGoodService.saveReturnGood(returngood);
				redirectAttributes.addFlashAttribute("message", "匹配失败");
				return "false";
			}
			}else{
				returngood.setStatus("0");
				returnGoodService.saveReturnGood(returngood);
				redirectAttributes.addFlashAttribute("message", "匹配失败");
				return "false";
				
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return "false";
		}
	}
	
	@RequestMapping(value="deleteReturnGood")
	@ResponseBody
	public String deleteReturnGood(Model model,HttpServletRequest req){
		try {
			Long id = Long.valueOf(req.getParameter("id"));
			returnGoodService.deleteReturnGood(id);
			return "true";
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return "false";
		}
	}
	
	@ModelAttribute("returngood")
	public ReturnGood getTask(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			return returnGoodService.findRg(id);
		}
		return null;
	}
	
	private String findInbillCode(Long preid){
		PreInBill preInBill = preInBillService.findByPreBillId(preid);
		if(preInBill.getInBillCode()==null){
			return null;
		}
		return preInBill.getInBillCode().toString();
	}
}
